﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Net.Http.Headers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ImgUpload
{
    public class RedirectImageRequests : IRule
    {
        private readonly string _path;
        public RedirectImageRequests(string path)
        {
            _path = path;
        }
        public void ApplyRule(RewriteContext context)
        {
            var request = context.HttpContext.Request;

            if (request.Path.ToString().IndexOf("HEAD") <= 0) return;
            //已经是默认地址 直接返回
            if (request.Path.StartsWithSegments(new PathString("/HEAD/default.png"))) return;
            string file = _path + request.Path.ToString().Replace("/", "\\");

            if (!File.Exists(file))
            {
                var response = context.HttpContext.Response;
                response.StatusCode = StatusCodes.Status302Found;
                context.Result = RuleResult.EndResponse;
                response.Headers[HeaderNames.Location] =
                      "/HEAD/default.png" + request.QueryString;
            }
        }
    }
}
